package com.cy.store.service.impl;

import com.cy.store.entity.Address;
import com.cy.store.entity.Order;
import com.cy.store.entity.OrderItem;
import com.cy.store.mapper.OrderMapper;
import com.cy.store.service.AddressService;
import com.cy.store.service.CartService;
import com.cy.store.service.OrderService;
import com.cy.store.service.ex.InsertException;
import com.cy.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CartService cartService;

    @Override
    public Order create(Integer aid, Integer uid, String username, Integer[] cids) {
        List<CartVO> list = cartService.getVOByCid(uid,cids);
        // 计算商品总价
        long allPrice = 0L;
        for (CartVO c :list) {
           allPrice +=
                   c.getRealPrice()
                           * c.getNum();
        }
        Address address = addressService.getByAid(aid, uid);
        // 订单数据
        Order order =new Order();
        order.setUid(uid);
        // 地址信息
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        // 支付总价
        order.setStatus(0);
        order.setTotalPrice(allPrice);
        // 日志
        Date date= new Date();
        order.setCreatedTime(date);
        order.setModifiedTime(date);
        order.setCreatedUser(username);
        order.setModifiedUser(username);
        // 插入数据
        Integer row = orderMapper.insertOrder(order);
        if(row != 1) throw new InsertException("订单数据未插入");

        for (CartVO c :list) {
            // 创建订单项数据对象
            OrderItem orderItem = new OrderItem();
            orderItem.setOid(order.getOid());
            orderItem.setPid(c.getPid());
            orderItem.setTitle(c.getTitle());
            orderItem.setImage(c.getImage());
            orderItem.setPrice(c.getRealPrice());
            orderItem.setNum(c.getNum());
            // 日志
            orderItem.setCreatedTime(date);
            orderItem.setModifiedTime(date);
            orderItem.setCreatedUser(username);
            orderItem.setModifiedUser(username);
            // 插入
            row = orderMapper.insertOrderItem(orderItem);
            if(row != 1) throw new InsertException("订单项数据未插入");
        }
        // 返回数据
        return order;
    }
}
